package com.itxiaoxiong.chat.service.impl;

import com.itxiaoxiong.chat.mapper.FriendMapper;
import com.itxiaoxiong.chat.pojo.*;
import com.itxiaoxiong.chat.service.FriendService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

@Slf4j
@Service
public class FriendServiceImpl implements FriendService {

    private final BlockingQueue<String> messageQueue = new LinkedBlockingQueue<>();
    @Autowired
    private FriendMapper friendMapper;

    @Override
    public User listName(String username) {
        return friendMapper.listName(username);
    }

    /*
        加好友
         */
    @Override
    public Result addFriend(FriendRelationship friendAdd) {
        boolean exists = friendMapper.checkIfFriendExists(friendAdd.getUserId1(), friendAdd.getUserId2());
        if (exists) {
            return Result.error("已经是好友，不能重复添加");
        }
        friendMapper.insert(friendAdd);
        return Result.success();
    }

    /*
   删除好友
    */
    @Override
    public Result deleteFriend(FriendRelationship friendDelete) {
        boolean exists = friendMapper.checkIfFriendExists(friendDelete.getUserId1(), friendDelete.getUserId2());
        if (!exists) {
            return Result.error("不是好友关系，无法删除");
        }
        friendMapper.delete(friendDelete);
        return Result.success();
    }

    /*
    查找好友
     */
    public List<FriendRelationship> getFriends(Integer userId) {

        return friendMapper.getFriendsByUserId(userId);
    }


    /*
    查找聊天记录
     */
    @Override
    public List<ChatMessage> getMessage(Integer userId1, Integer userId2) {
        return friendMapper.getMessages(userId1, userId2);
    }

    /*
    发消息
     */
    @Override
    public void addMessage(ChatMessage chatMessage) {
        chatMessage.setSendTime(LocalDateTime.now());
        try {
            friendMapper.addMessage(chatMessage);
        } catch (Exception e) {
            // 在这里进行异常处理，比如记录错误日志等
            log.error("插入消息时发生错误: {}", e.getMessage());
        }
    }


    /*
    删除聊天记录
     */
    @Override
    public void deleteMessage(ChatMessage chatMessage) {
        friendMapper.deleteMessage(chatMessage);
    }

    /*
    发送图片
     */
    @Override
    public void addFile(ChatMessage chatMessage) {
        chatMessage.setSendTime(LocalDateTime.now());
        friendMapper.addFile(chatMessage);
    }

}
